package cn.blt.config.mp;

import cn.blt.security.auth.entity.SysUser;
import com.baomidou.mybatisplus.core.handlers.MetaObjectHandler;
import lombok.extern.slf4j.Slf4j;
import org.apache.ibatis.reflection.MetaObject;
import org.springframework.security.core.Authentication;
import org.springframework.security.core.context.SecurityContextHolder;
import org.springframework.stereotype.Component;

import java.util.Date;

/**
 * Mybatis-plus 填充类
 * @author run
 * @date 2022/08/27
 */
@Slf4j
@Component
public class MyMetaObjectHandler implements MetaObjectHandler {

    @Override
    public void insertFill(MetaObject metaObject) {
        Authentication authentication = SecurityContextHolder.getContext().getAuthentication();
        if (authentication != null) {
            SysUser user = (SysUser) authentication.getPrincipal();
            this.strictInsertFill(metaObject,"createBy", user::getId,Long.class);
            this.strictInsertFill(metaObject,"updateBy", user::getId,Long.class);
        }
        this.strictInsertFill(metaObject, "createDate", Date::new, Date.class);
        this.strictInsertFill(metaObject, "updateDate", Date::new, Date.class);
    }


    @Override
    public void updateFill(MetaObject metaObject) {
        this.strictUpdateFill(metaObject, "updateDate", Date::new, Date.class);
        Authentication authentication = SecurityContextHolder.getContext().getAuthentication();
        if (authentication != null) {
            SysUser user = (SysUser) authentication.getPrincipal();
            this.strictUpdateFill(metaObject,"updateBy", user::getId,Long.class);
        }
    }
}
